package com.runen.wnhz.runen.ui.activity.main;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.AtOncePayBean;
import com.runen.wnhz.runen.common.alipay.PayResult;
import com.runen.wnhz.runen.common.login.Wx.WeiXinPayBean;
import com.runen.wnhz.runen.common.login.Wx.WeiXinUtils;
import com.runen.wnhz.runen.common.popwindow.PayPasswordDialog;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.Base64Utils;
import com.runen.wnhz.runen.common.utils.JumpUtlis;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.StatusBarCompatUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.ui.activity.BaseActivity;
import com.runen.wnhz.runen.ui.activity.mine.ChangePayPasswordActivity;
import com.runen.wnhz.runen.ui.activity.mine.MyOrderActivity;
import com.runen.wnhz.runen.widget.TitleBuilder;

import java.io.IOException;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class OrderSureActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.text_orderTotalFee)
    TextView textOrderTotalFee;
    @BindView(R.id.radio_balancePay)
    RadioButton radioBalancePay;
    @BindView(R.id.radio_weChatPay)
    RadioButton radioWeChatPay;
    @BindView(R.id.radio_aliPay)
    RadioButton radioAliPay;
    @BindView(R.id.radio_unionPay)
    RadioButton radioUnionPay;
    @BindView(R.id.btn_atOncePay)
    Button btnAtOncePay;
    private String orderNo = "";
    private String token;
    private int type = 3;
    private String rinfo;
    private boolean orderNoDecode;//订单编号已经解码
    private double orderTotalFee;

    private String newPasd;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Map<String, String> map = (Map<String, String>) msg.obj;
            PayResult payResult = new PayResult(map);
            /**
             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            //   Log.e("-----", resultInfo + "---" + resultStatus);
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                ToastUtil.showToast("支付成功");
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                ToastUtil.showToast("支付失败");
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutView() {
        return R.layout.pay_way_choose_layout;
    }

    @Override
    protected void onTitleClickListen(TitleBuilder.TitleButton clicked) {

    }

    @Override
    protected void initStart() {
        init();
        setListener();
    }

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        mTitleBuilder.setLeftDrawable(R.mipmap.icon_back);
        mTitleBuilder.setMiddleTitleText("订单支付");
        mTitleBuilder.setMiddleTitleTextColor(Color.WHITE);
        mTitleBuilder.setLeftTextOrImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {

    }

    private void init() {
        StatusBarCompatUtils.getInstance().TranslucentStatusBar(this, R.color.title_green);
        ButterKnife.bind(this);
        radioBalancePay.setChecked(true);
        orderNo = getIntent().getStringExtra("orderNo");
        orderTotalFee = getIntent().getDoubleExtra("orderTotalFee", 0D);
        textOrderTotalFee.setText("订单金额:￥" + orderTotalFee);
        if (ACacheUtlis.getInstance() != null) {
            if (ACacheUtlis.getInstance().getReqeustUser(this) != null) {
                token = ACacheUtlis.getInstance().getReqeustUser(this).getToken();
            }
        }
    }

    private void setListener() {
        radioBalancePay.setOnCheckedChangeListener(this);
        radioWeChatPay.setOnCheckedChangeListener(this);
        radioAliPay.setOnCheckedChangeListener(this);
        radioUnionPay.setOnCheckedChangeListener(this);
    }

    @OnClick({R.id.btn_atOncePay})
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.btn_atOncePay:
                if(type == 3){
                    needtoSetPasd();
                }else {
                    atOncePay();
                }
                break;
        }
    }

    private void needtoSetPasd() {
        if (token != null && type == 3) {
            FormBody formBody;

                formBody = new FormBody.Builder()
                        .add("token", token)
                        .build();

            Request request = new Request.Builder().url(NetUtils.ORDER_SETMoney).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    try {
                        handleOrderAtOncePay(response,1);
                    } catch (IOException e) {
                        e.printStackTrace();
                        ToastUtil.showToast("数据请求出现异常");
                    }
                }
            });
        }
    }

    /**立即支付*/
    private void atOncePay() {
        if (token != null && type != 0) {
            FormBody formBody;
           String base64Pasd =  Base64Utils.encode(newPasd);

            if (!"".equals(orderNo)) {
                String tempOrderNo;
                if (!orderNoDecode) {
                    String temp = Base64Utils.decode(orderNo);
                    tempOrderNo = temp.substring(3, temp.indexOf("HACHA"));
                    orderNoDecode = true;
                } else {
                    tempOrderNo = orderNo;
                }

                if(type ==3 ){
                    formBody = new FormBody.Builder()
                            .add("token", token)
                            .add("pay_password",base64Pasd)
                            .add("order_no", tempOrderNo)
                            .add("type", String.valueOf(type))
                            .build();
                }else{
                    formBody = new FormBody.Builder()
                            .add("token", token)
                            .add("order_no", tempOrderNo)
                            .add("type", String.valueOf(type))
                            .build();
                }

            } else {
                formBody = new FormBody.Builder()
                        .add("token", token)
                        .add("order_no", "")
                        .add("type", String.valueOf(type))
                        .build();
            }
            Request request = new Request.Builder().url(NetUtils.AT_ONCE_PAY).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    try {
                        handleOrderAtOncePay(response,2);
                    } catch (IOException e) {
                        e.printStackTrace();
                        ToastUtil.showToast("数据请求出现异常");
                    }
                }
            });
        }
    }

    private void weixinPay(AtOncePayBean.DataBean.RinfoBean info){

        WeiXinPayBean weiXinPayBean = new WeiXinPayBean(info.getAppid(), info.getNoncestr(),
                 getPackageName(), info.getPartnerid(), info.getPrepayid(),Integer.parseInt(info.getTimestamp()), info.getSign());

/*

        PayReq req = new PayReq();
        req.appId = weiXinPayBean.getAppid();
        req.partnerId = weiXinPayBean.getPartnerid();
        req.prepayId = weiXinPayBean.getPrepayid();
        req.nonceStr = weiXinPayBean.getNoncestr();
        req.timeStamp = weiXinPayBean.getTimestamp() + "";
        req.packageValue = "Sign=WXPay";

        req.sign = weiXinPayBean.getSign();*/
        WeiXinUtils.getInstance().wxPay(weiXinPayBean);


    }

    private void zhiFuBaoPay(AtOncePayBean atOncePayBean) {
        AtOncePayBean.DataBean data = atOncePayBean.getData();
        final String ali_info = data.getAli_info();
//        final String orderInfo = ali_info.substring(ali_info.indexOf("app_id"));
        String[] splitAliInfo = ali_info.split("&");
        for (String split : splitAliInfo) {
            System.out.println("99999999 == " + split);
        }
//        BizContentBean bizContentBean = new Gson().fromJson(splitAliInfo[2].split("=")[1], BizContentBean.class);
//        final String orderInfo = "_input_charset=\"" + splitAliInfo[3].split("=")[1] + "\"&body=\"" + bizContentBean.getBody() + "\"&notify_url=\"" + splitAliInfo[6].split("=")[1] + "\"&out_trade_no=\"" + bizContentBean.getOut_trade_no() + "\"&partner=\"" + bizContentBean.get;

        Runnable payRunable = new Runnable() {
            @Override
            public void run() {
                PayTask payTask = new PayTask(OrderSureActivity.this);
                Map<String, String> result = payTask.payV2(ali_info, true);
                Message msg = new Message();
//                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        };
        Thread thread = new Thread(payRunable);
        thread.start();
    }

    private void handleOrderAtOncePay(Response response, final int val) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            final String json = responseBody.string();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("AtOncePayBean == " + json);
                    AtOncePayBean atOncePayBean = new Gson().fromJson(json, AtOncePayBean.class);
                    if ("1".equals(atOncePayBean.getRe())) {
                        ToastUtil.showToast(atOncePayBean.getInfo());
//                        rinfo = atOncePayBean.getData().getRinfo();
                        if(val == 1){
                           String  is_set = atOncePayBean.getData().getIs_set();
                           if(is_set.equals("1")){
                               JumpUtlis.getInstance().jumpActivity(OrderSureActivity.this, ChangePayPasswordActivity.class);
                           }else{
                               final PayPasswordDialog dialog=new PayPasswordDialog(OrderSureActivity.this,R.style.mydialog);
                               dialog.setDialogClick(new PayPasswordDialog.DialogClick() {
                                   @Override
                                   public void doConfirm(String password) {
                                       newPasd = password;

                                       dialog.dismiss();
                                       Toast.makeText(OrderSureActivity.this,password,Toast.LENGTH_LONG).show();

                                       atOncePay();
                                   }
                               });
                               dialog.show();
                           }
                        }else {
                            orderNo = atOncePayBean.getData().getOrder_no();
                            if (type == 1) {
                                zhiFuBaoPay(atOncePayBean);
                            } else if (type == 3) {
                                JumpUtlis.getInstance().jumpActivity(OrderSureActivity.this, MyOrderActivity.class);
                                finish();
                            } else if (type == 2) {
                                AtOncePayBean.DataBean.RinfoBean rinfoBean = atOncePayBean.getData().getRinfo();
                                weixinPay(rinfoBean);
                            }
                        }
                    } else if ("0".equals(atOncePayBean.getRe())) {
                        ToastUtil.showToast(atOncePayBean.getInfo());
                    }

                }
            });
        }

    }

    private void payJudge() {
        if (type == 3) {

        }
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        switch (compoundButton.getId()) {
            case R.id.radio_balancePay:
                if (b) {
                    type = 3;
                }
                break;
            case R.id.radio_weChatPay:
                if (b) {
                    type = 2;
                }
                break;
            case R.id.radio_aliPay:
                if (b) {
                    type = 1;
                }
                break;
            case R.id.radio_unionPay:
                if (b) {
                    type = 4;
                }
                break;
        }
    }
}
